package com.liy.cloud.base.rest;

import com.liy.cloud.auth.client.utils.RequestUtil;
import com.liy.cloud.common.base.entity.BaseEquInfoEntity;
import com.liy.cloud.common.base.service.BaseEquInfoService;
import com.liy.cloud.common.feign.api.SysFeignClient;
import com.liy.cloud.common.vo.EquInfoVO;
import com.liy.cloud.common.vo.EquLayoutVO;
import com.das.framework.common.annotation.ActionPermission;
import com.das.framework.common.annotation.MethodPermission;
import com.das.framework.common.constants.PermissionCodes;
import com.das.framework.common.extvo.ResultVO;
import com.das.framework.common.vo.PageVO;
import com.das.framework.common.web.controller.BaseCrudController;
import com.das.framework.common.web.extcall.RestTemplateUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * @Author: zhangw
 * @Date: 2018/6/22  9:08
 * @Description: 设备信息管理
 **/
@RestController
@RequestMapping("equinfo")
@ActionPermission(code = "BASE.EQUINFO", description = "设备信息管理")
public class BaseEquInfoRest extends BaseCrudController<BaseEquInfoService, BaseEquInfoEntity> {

    protected static Logger log = LoggerFactory.getLogger(BaseEquInfoRest.class);

    @Value("${server.port}")
    private String port;
    @Autowired
    private BaseEquInfoService baseEquInfoService;
    @Autowired
    private SysFeignClient sysFeignClient;

    @Autowired
    private RestTemplateUtil bizSysUtil;

    /**
     * @Description: 获取设备目录树的结构数据;
     **/
    @RequestMapping(value = "/get/tree", method = RequestMethod.GET)
    public PageVO getTreeData() {
        PageVO pageVO = new PageVO();
        try {
//            String url = bizSysUtil.getSysServerUrl() + "/dict/item/select/typecode";
//            resultVO = bizSysUtil.get(url, ResultVO.class);
            Map<String, Object> params = new HashMap<>();
            pageVO = sysFeignClient.getDictItemSelectTypecode(RequestUtil.map2urlparam(params), 1000,1);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            pageVO.setStatus("500");
            pageVO.setMessage("查询时发生错误:" + e.getMessage());
        }
        return pageVO;
    }


    @RequestMapping(
            value = {"/query/codeId", "/query/codeId/{pageSize}", "/query/codeId/{pageSize}/{pageNo}"},
            method = {RequestMethod.GET, RequestMethod.POST}
    )
    @ResponseBody
    @MethodPermission(codes = {"SEARCH"}, description = "列表查询"
    )
    public PageVO<BaseEquInfoEntity> list(BaseEquInfoEntity entity,
                                          @PathVariable(value = "pageSize", required = false) Integer pageSize,
                                          @PathVariable(value = "pageNo", required = false) Integer pageNo) {
        PageVO<BaseEquInfoEntity> page = new PageVO();
        if (pageNo != null) {
            page.setPageNo(pageNo);
        }

        if (pageSize != null) {
            page.setPageSize(pageSize);
        }

        try {
            this.baseEquInfoService.queryByTypeCodeOrDiviceType(entity, page);
        } catch (Exception var6) {
            log.error("查询数据出错!", var6);
            page.setStatus("500");
            page.setMessage(var6.getMessage());
        }

        return page;
    }

    @RequestMapping(value = {"/addBaseEquInfo"}, method = {RequestMethod.POST})
    @MethodPermission(codes = {"INSERT"}, description = "新增")

    public ResultVO addBaseEquInfo(@RequestBody @Valid BaseEquInfoEntity baseEquInfoEntity) {

        try {

            //新增前先校验编号是否重复
            BaseEquInfoEntity equInfo = this.baseService.findById(baseEquInfoEntity.getId());
            if (equInfo != null) {
                return new ResultVO(false, "设备编号存在重复，请重新输入", "500");
            }

            baseEquInfoService.addBaseEquInfo(baseEquInfoEntity);
            return new ResultVO(true, "新增成功", "200", baseEquInfoEntity);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return new ResultVO(false, "新增时发生错误:" + e.getMessage(), "500");
        }
    }

    /**
     * @Description: 批量删除
     **/
    @PostMapping("/delete/batch")
    public ResultVO deleteBatch(@RequestBody() List<String> ids) {
        try {
            baseEquInfoService.deleteBatch(ids);
            return new ResultVO(true, "删除成功:", "200");
        } catch (Exception var4) {
            log.error(var4.getMessage(), var4);
            return new ResultVO(false, "删除时发生错误:" + var4.getMessage(), "500");
        }
    }
    
    @PostMapping("/update/batchAngle")
    public ResultVO updateAngleBatch(@RequestBody() EquLayoutVO layoutVO) {
        try {
            baseEquInfoService.updateAngleBatch(layoutVO);
            return new ResultVO(true, "保存成功:", "200");
        } catch (Exception var4) {
            log.error(var4.getMessage(), var4);
            return new ResultVO(false, "保存时发生错误:" + var4.getMessage(), "500");
        }
    }

    /**
     * 监控系统调用，查询需要监控的设备种类下的设备列表
     * @author shitou
     * @param
     * @param pageSize
     * @param pageNo
     * @return
     */
    @RequestMapping({"/query/monitor", "/query/monitor/{pageSize}/{pageNo}"})
    @MethodPermission(codes = PermissionCodes.SEARCH, description = "查询")
    public PageVO<BaseEquInfoEntity> queryByMonitor(BaseEquInfoEntity equInfo,
                                                     @PathVariable(value = "pageSize", required = false) Integer pageSize,
                                                     @PathVariable(value = "pageNo", required = false) Integer pageNo) {
        PageVO<BaseEquInfoEntity> page = new PageVO<BaseEquInfoEntity>();
        if (pageNo != null) {
            page.setPageNo(pageNo);
        }
        if (pageSize != null) {
            page.setPageSize(pageSize);
        }
        ResultVO resultVO = new ResultVO();
        try {

            resultVO.setData(baseEquInfoService.findByMonitor(equInfo, page));
        } catch (Exception e) {
            log.error("查询数据出错!", e);
            resultVO.setSuccess(false, "500");
            resultVO.setMessage("查询时发生错误:" + e.getMessage());
        }
        return page;
    }
    
    /**
     * 查询设备树信息，带分类
     * 	注：分类下没有设备时 分类节点不会显示
     * @author shitou
     * @return
     */
    @RequestMapping(value = "/groupData", method = RequestMethod.GET)
    public ResultVO getEquGroupTable(EquInfoVO vo) {
        ResultVO resultVO = new ResultVO();

        try {
        	List<EquInfoVO> list = baseEquInfoService.findAllAndType(vo);
        	
        	Map<String, String> map = new HashMap<>();
        	
        	List<EquInfoVO> nodeList = new ArrayList<>();
        	for (EquInfoVO equInfoVO : list) {
				
        		if(map.get(equInfoVO.getmType()) == null) {
        			
        			EquInfoVO group = new EquInfoVO();
        			group.setId("_group");
        			group.setsType(equInfoVO.getsType());
        			group.setsTypeName(equInfoVO.getsTypeName());
        			group.setmType(equInfoVO.getmType());
        			group.setmTypeName(equInfoVO.getmTypeName());
        			nodeList.add(group);
        			map.put(equInfoVO.getmType(), equInfoVO.getmType());
        		}
        		nodeList.add(equInfoVO);
			}
        	resultVO.setData(nodeList);
        	
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            resultVO.setSuccess(false, "500");
            resultVO.setMessage("查询时发生错误:" + e.getMessage());
        }
        return resultVO;
    }

    /**
     * @Author:  liyang
     * @Date:    2018/8/14  16:38
     * @Description: 根据 设备大类编号 --> 设备小类 -->  设备明细信息
     *
     **/
    @RequestMapping(value = "get/type/all/info" , method = RequestMethod.POST)
    public ResultVO getEquInfoListByTypeCode(@RequestBody Map<String,List<String>> map) {
        // 当前车站 设备种类下 所有的设备明细
        List<BaseEquInfoEntity>  allEquInfoList = new ArrayList<>();
        List<String> deviceTypes = map.get("deviceTypes");  // 设备种类
        List<String> stationIds = map.get("stationIds");   // 车站编号
        try {
            for(String stationId : stationIds){
                for(String deviceType : deviceTypes){
                    BaseEquInfoEntity query = new BaseEquInfoEntity();
                    query.setStationid(stationId);  // 车站编号
                    query.setDevicetype(deviceType); // 设备种类
                    allEquInfoList.addAll( baseEquInfoService.findList(query));
                }
            }
            return new ResultVO(true, "查询成功!", "200", allEquInfoList);
        } catch (Exception var4) {
            log.error(var4.getMessage(), var4);
            return new ResultVO(false, "查询时发生错误:" + var4.getMessage(), "500");
        }
    }


    /**
     *
     * 功能描述: 根据参数params查询设备信息
     *
     * @param: params：Map中包含车站编号 stationid，设备类型集合 devicetypes
     * @return:
     * @auther: libs
     * @date: 2018/8/14 9:29
     */
    @RequestMapping(
            value = {"/get/by/params", "/get/by/params/{pageSize}", "/get/by/params/{pageSize}/{pageNo}"},
            method = {RequestMethod.POST}
    )
    @ResponseBody
    @MethodPermission(codes = {"SEARCH"}, description = "列表查询")
    public PageVO<BaseEquInfoEntity> getByParams(@RequestBody() Map<String, Object> params, @PathVariable(value = "pageSize",required = false) Integer pageSize, @PathVariable(value = "pageNo",required = false) Integer pageNo) {
        PageVO page = new PageVO(pageNo, pageSize);
        try {
            page.setResults(this.baseEquInfoService.getByParams(params, page));
        } catch (Exception e) {
            log.error("查询数据出错!", e);
            page.setStatus("500");
            page.setMessage("查询时发生错误:" + e.getMessage());
        }
        return page;
    }

    /**
     * 根据车站编号集合 stationIds, 设备大类集合 typeCodes, 设备种类集合 deviceTypes, 设备编号（模糊） deviceId, 设备名（模糊） deviceName 查询设备信息
     *
     * @param params
     * @param pageNo
     * @param pageSize
     * @return
     * @auther libs
     * @date 2018/11/13 13:55
     */
    @RequestMapping(
        value = {"/get/info", "/get/info/{pageSize}", "/get/info/{pageSize}/{pageNo}"},
        method = {RequestMethod.POST}
    )
    @ResponseBody
    @MethodPermission(
        codes = {"SEARCH"},
        description = "列表查询"
    )
    public PageVO getInfo(@RequestBody Map<String, Object> params, @PathVariable(value = "pageSize",required = false) Integer pageSize, @PathVariable(value = "pageNo",required = false) Integer pageNo) {
        PageVO page = new PageVO(pageNo, pageSize);
        try {
            baseService.getInfoByPage(params, page);
        } catch (Exception e) {
            log.error("查询数据出错!", e);
            page.setStatus("500");
            page.setMessage(e.getMessage());
        }
        return page;
    }

    /**
     * 验证设备
     * @param params 查询条件
     * @return
     */
    @PostMapping("/validate")
    @GetMapping
    public ResultVO validateEqu(@RequestBody() Map<String, Object> params) {
        try {
            String equId = (String)params.get("equId");//设备编号
            if(equId == null){
                return new ResultVO(true, "json格式错误请检查,equId", "500");
            }
            BaseEquInfoEntity equInfo = this.baseService.findById(equId);
            if(equInfo != null){
                return new ResultVO(true, "存在该设备", "200");
            }else{
                return new ResultVO(false, "不存在该设备", "500");
            }
        } catch (Exception var4) {
            log.error(var4.getMessage(), var4);
            return new ResultVO(false, "验证时发生错误:" + var4.getMessage(), "500");
        }
    }

    @GetMapping("/type/tvm/num")
    public ResultVO getTypeTvmNum() {
        ResultVO resultVO = new ResultVO();
        try {
            resultVO.setData(baseEquInfoService.getEquTypeTvmNum());
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            resultVO.setSuccess(false, "500");
            resultVO.setMessage("查询时发生错误:" + e.getMessage());
        }
        return resultVO;
    }

    @GetMapping("/type/avm/num")
    public ResultVO getTypeAvmNum() {
        ResultVO resultVO = new ResultVO();
        try {
            resultVO.setData(baseEquInfoService.getEquTypeAvmNum());
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            resultVO.setSuccess(false, "500");
            resultVO.setMessage("查询时发生错误:" + e.getMessage());
        }
        return resultVO;
    }

    @GetMapping("/type/bom/num")
    public ResultVO getTypeBomNum() {
        ResultVO resultVO = new ResultVO();
        try {
            resultVO.setData(baseEquInfoService.getEquTypeBomNum());
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            resultVO.setSuccess(false, "500");
            resultVO.setMessage("查询时发生错误:" + e.getMessage());
        }
        return resultVO;
    }

    @GetMapping("/type/agm/num")
    public ResultVO getTypeAgmNum() {
        ResultVO resultVO = new ResultVO();
        try {
            resultVO.setData(baseEquInfoService.getEquTypeAgmNum());
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            resultVO.setSuccess(false, "500");
            resultVO.setMessage("查询时发生错误:" + e.getMessage());
        }
        return resultVO;
    }
}
